package com.xsz.order.service.impl;

import com.xsz.common.service.impl.BaseService;
import com.xsz.common.util.KeyUtil;
import com.xsz.common.util.MD5Utils;
import com.xsz.order.dao.OrderMapper;
import com.xsz.order.domain.CreateOrderForm;
import com.xsz.order.domain.QueryOrderForm;
import com.xsz.order.entity.Order;
import com.xsz.order.service.OrderService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Objects;

/**
 * @author zsj55
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class OrderServiceImpl extends BaseService<Order> implements OrderService {

    private OrderMapper orderMapper;
    /**
     * 根据前端传值添加相应订单记录
     *
     * @param createOrderForm 添加订单form
     */
    @Override
    public int createOrderByCreateOrderForm(CreateOrderForm createOrderForm) {
        Order order = new Order();
        BeanUtils.copyProperties(createOrderForm, order);
        order.setOrderId(KeyUtil.genUniqueKey());
        return orderMapper.insert(order);
    }

    /**
     * 根据前端传值查询相应记录
     *
     * @param queryOrderForm 查询form
     * @return
     */
    @Override
    public List<Order> getOrderByQueryOrderForm(QueryOrderForm queryOrderForm) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", queryOrderForm.getUserId());

        if (StringUtils.hasText(queryOrderForm.getOrderId())){
            criteria.andEqualTo("orderId", queryOrderForm.getOrderId());
        }

        if (StringUtils.hasText(queryOrderForm.getOrderUserName())){
            criteria.andLike("orderUserName", queryOrderForm.getOrderUserName());
        }

        if (CollectionUtils.isNotEmpty(queryOrderForm.getStatuses())){
            criteria.andIn("status", queryOrderForm.getStatuses());
        }

        if (Objects.nonNull(queryOrderForm.getTakeMealTimeLower())){
            criteria.andGreaterThanOrEqualTo("takeMealTime", queryOrderForm.getTakeMealTimeLower());
        }
        if (Objects.nonNull(queryOrderForm.getTakeMealTimeUpper())){
            criteria.andLessThanOrEqualTo("takeMealTime", queryOrderForm.getTakeMealTimeUpper());
        }
        return selectByExample(example);
    }

    /**
     * 根据订单ID查找相应记录
     *
     * @param orderId 订单ID
     * @return
     */
    @Override
    public Order getOrderById(String orderId) {
        return orderMapper.selectByPrimaryKey(orderId);
    }
}
